package com.mce.nebula.service;

import com.mce.nebula.common.UuidGenerator;
import com.mce.nebula.entity.User;
import com.mce.nebula.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 用户服务，对应Python的UserService
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    /**
     * 根据用户名查找用户
     */
    public Optional<User> findByUsername(String username) {
        return userRepository.findByNickName(username);
    }
    
    /**
     * 根据邮箱查找用户
     */
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    /**
     * 根据手机号查找用户
     */
    public Optional<User> findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }
    
    /**
     * 创建用户
     */
    @Transactional
    public User createUser(String nickName, String email, String password, String enterpriseId) {
        // 检查用户名是否已存在
        if (userRepository.existsByNickName(nickName)) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(email)) {
            throw new RuntimeException("邮箱已存在");
        }
        
        User user = new User();
        user.setNickName(nickName);
        user.setEmail(email);
        user.setPassword(passwordEncoder.encode(password));
        user.setEnterpriseId(enterpriseId);
        user.setIsActive(true);
        
        // 如果是第一个用户，设置为系统管理员
        if (userRepository.count() == 0) {
            user.setSysAdmin(true);
            log.info("Setting first user as system admin: {}", nickName);
        } else {
            user.setSysAdmin(false);
        }
        
        return userRepository.save(user);
    }
    
    /**
     * 手机号注册
     */
    @Transactional
    public User registerByPhone(String enterpriseId, String phone, String nickName) {
        // 检查手机号是否已注册
        if (userRepository.existsByPhone(phone)) {
            throw new RuntimeException("该手机号已注册");
        }
        
        // 检查用户名是否已存在
        if (userRepository.existsByNickName(nickName)) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        user.setPhone(phone);
        user.setNickName(nickName);
        user.setEmail(phone + "@temp.com"); // 临时邮箱
        user.setIsActive(true);
        user.setEnterpriseId(enterpriseId);
        
        // 如果是第一个用户，设置为系统管理员
        if (userRepository.count() == 0) {
            user.setSysAdmin(true);
        }
        
        return userRepository.save(user);
    }
    
    /**
     * 获取企业用户列表
     */
    public List<User> getEnterpriseUsers(String enterpriseId) {
        return userRepository.findByEnterpriseId(enterpriseId);
    }
    
    /**
     * 激活用户
     */
    @Transactional
    public void activateUser(Long userId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setIsActive(true);
        userRepository.save(user);
    }
    
    /**
     * 禁用用户
     */
    @Transactional
    public void deactivateUser(Long userId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setIsActive(false);
        userRepository.save(user);
    }
    
    /**
     * 设置用户为系统管理员
     */
    @Transactional
    public void setSysAdmin(Long userId, boolean isSysAdmin) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        user.setSysAdmin(isSysAdmin);
        userRepository.save(user);
    }
    
    /**
     * 更新用户信息
     */
    @Transactional
    public User updateUser(Long userId, String realName, String phone, String logo) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        if (realName != null) {
            user.setRealName(realName);
        }
        if (phone != null) {
            user.setPhone(phone);
        }
        if (logo != null) {
            user.setLogo(logo);
        }
        
        return userRepository.save(user);
    }
    
    /**
     * 检查用户是否存在
     */
    public boolean userExists(String username) {
        return userRepository.existsByNickName(username);
    }
    
    /**
     * 获取所有激活的用户
     */
    public List<User> getActiveUsers() {
        return userRepository.findByIsActiveTrue();
    }
    
    /**
     * 获取所有系统管理员
     */
    public List<User> getSysAdmins() {
        return userRepository.findBySysAdminTrue();
    }
}





